import json
import os
from pathlib import Path
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 文件路径可以通过环境变量或配置文件传递，默认值为当前目录下的 account.json
file_path = os.getenv('ACCOUNT_FILE_PATH', 'account.json')


class Account:
    def __init__(self, account_id, category, account, amount, timestamp, description):
        self.account_id = account_id
        self.category = category
        self.account = account
        self.amount = amount
        self.timestamp = timestamp
        self.description = description

    def to_dict(self):
        return {
            "account_id": self.account_id,
            "category": self.category,
            "account": self.account,
            "amount": self.amount,
            "timestamp": self.timestamp,
            "description": self.description
        }

    @classmethod
    def from_dict(cls, data):
        return cls(
            account_id=data["account_id"],
            category=data["category"],
            account=data["account"],
            amount=data["amount"],
            timestamp=data["timestamp"],
            description=data["description"]
        )


class AccountManager:
    def __init__(self, file_path):
        self.file_path = Path(file_path).resolve()
        self.accounts = []
        self._load_accounts()

    def _load_accounts(self):
        if self.file_path.exists():
            try:
                with open(self.file_path, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    self.accounts = [Account.from_dict(account) for account in data]
            except (IOError, json.JSONDecodeError) as e:
                logging.error(f"无法从文件加载帐户 {self.file_path}: {e}")
                self.accounts = []
        else:
            self.accounts = []

    def _save_accounts(self):
        try:
            temp_file_path = self.file_path.with_suffix('.tmp')
            with open(temp_file_path, 'w', encoding='utf-8') as f:
                json.dump([account.to_dict() for account in self.accounts], f, ensure_ascii=False, indent=4)
            os.replace(temp_file_path, self.file_path)
        except (IOError, OSError) as e:
            logging.error(f"写入文件失败 {self.file_path}: {e}")

    def add_account(self, account):
        self.accounts.append(account)
        self._save_accounts()

    def remove_account(self, account_id):
        if not account_id:
            logging.warning("提供的account_id无效.")
            return
        self.accounts = [account for account in self.accounts if account.account_id != account_id]
        self._save_accounts()

    def update_account(self, account_id, **kwargs):
        if not account_id:
            logging.warning("提供的account_id无效.")
            return
        for account in self.accounts:
            if account.account_id == account_id:
                for key, value in kwargs.items():
                    if hasattr(account, key):
                        setattr(account, key, value)
                self._save_accounts()
                return
        logging.warning(f"ID为的帐户 {account_id} 未找到.")

    def get_account(self, account_id):
        if not account_id:
            logging.warning("提供的account_id无效.")
            return None
        for account in self.accounts:
            if account.account_id == account_id:
                return account
        logging.warning(f"ID为的帐户 {account_id} 未找到.")
        return None

    def get_all_accounts(self):
        return self.accounts
